﻿import wsgiref.handlers
import os
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.db import GqlQuery
from google.appengine.api import urlfetch

from models import *   
 
class MainPage(webapp.RequestHandler):
	def get(self):
		template_values = {}
		user = Usuario().getCurrentUser()
		propostas = Proposta.all().order('-data')		
		if user:
			url = users.create_logout_url(self.request.uri)
			url_linktext = 'Logout'
			status = 'logado'
		else:
			url = users.create_login_url(self.request.uri)
			url_linktext = 'Login'
			status = ''
		
		template_values = { 'propostas' : propostas,
							'url': url,
							'user':user,
							'url_linktext': url_linktext,
							'status': status
							}	
		path = os.path.join(os.path.dirname(__file__), 'views/index.html')
		self.response.out.write(template.render(path,template_values))


class Login(webapp.RequestHandler):
	def get(self):	
		template_values = {}
		if self.request.get('logout') == '1':
			self.logoutConnect()
			return
		self.loginConnect()	
		user = Usuario().getCurrentUser()	
		if user:
			url = users.create_logout_url(self.request.uri)
			url_linktext = 'Logout'
			status = 'logado'
		else:
			url = users.create_login_url(self.request.uri)
			url_linktext = 'Login'
			status = ''
		template_values = { 
							'url': url,
							'user':user,							
							'url_linktext': url_linktext,
							'status': status
							}		
		path = os.path.join(os.path.dirname(__file__), 'views/index.html')
		self.response.out.write(template.render(path,template_values))		
		
	def loginConnect(self):
		from appengine_utilities.sessions import Session
		user = Usuario().all().filter("id =",self.request.get("id")).get()
		if user:
			self.session = Session()
			self.session['user'] = user
			print("1")
		else:
			print("0")

	def logoutConnect(self):
		from appengine_utilities.sessions import Session
		self.session = Session()
		self.session['user'] = ''	
			
		
class Publicadas(webapp.RequestHandler):
	def get(self):
		template_values = {}
		page = 1
		category = ''
		numero = 5		
		if self.request.get("page"):
			page = self.request.get("page")			
		n = (int(page) * numero) - numero		
		if self.request.get('category'):
			category = self.request.get('category')
			cont = Proposta.all().filter("categoria =",category).count()
			propostas = Proposta.all().filter("categoria =",category).order('-rank').fetch(numero,n)
		else:
			propostas = Proposta.all().order('-rank').fetch(numero,n)		
			cont = Proposta.all().count()
		paginas = pagination(cont,numero)	
		user = Usuario().getCurrentUser()	
		if user:
			url = users.create_logout_url(self.request.uri)
			url_linktext = 'Logout'
			status = 'logado'
		else:
			url = users.create_login_url(self.request.uri)
			url_linktext = 'Login'
			status = ''
		
		#p = []
		for proposta in propostas:
			proposta.id = str(proposta.key())
			

		resource = {'title': "Democracia 2 - Top Actions", 'pagename': "Top Actions"}
				
		template_values = { 'url': url,
							'url_linktext': url_linktext,
							'status': status,
							'paginas': paginas,
							'category': category,
							'user': user,
							'propostas': propostas,
							'resource': resource
							}
		path = os.path.join(os.path.dirname(__file__), 'views/publicadas.html')
		self.response.out.write(template.render(path,template_values))	

class Novas(webapp.RequestHandler):
	def get(self):
		template_values = {}
		page = 1
		category = ''
		if self.request.get("page"):
			page = self.request.get("page")		
		numero = 5		
		n = (int(page) * numero) - numero
		if self.request.get('category'):
			category = self.request.get('category')
			cont = Proposta.all().filter("categoria =",category).count()
			propostas = Proposta.all().filter("categoria =",category).order('-data').fetch(numero,n)
		else:
			propostas = Proposta.all().order('-data').fetch(numero,n)		
			cont = Proposta.all().count()			
		paginas = pagination(cont,numero)
		user = Usuario().getCurrentUser()	
		if user:
			url = users.create_logout_url(self.request.uri)
			url_linktext = 'Logout'
			status = 'logado'
		else:
			url = users.create_login_url(self.request.uri)
			url_linktext = 'Login'
			status = ''		
			
		for proposta in propostas:
			proposta.id = str(proposta.key())			
		
		resource = {'title': "Democracia 2 - New Actions", 'pagename': "New Actions"}
			
		template_values = { 'url': url,
							'url_linktext': url_linktext,
							'status': status,
							'paginas': paginas,
							'user': user,
							'category': category,
							'resource': resource,
							'propostas': propostas 
							}
		path = os.path.join(os.path.dirname(__file__), 'views/novas.html')
		self.response.out.write(template.render(path,template_values))
	
class Enviar(webapp.RequestHandler):
	def get(self):
		template_values = {}
		user = Usuario().getCurrentUser()		
		resource = {'title': "Democracia 2 - Submit", 'pagename': "Submit"}		
		template_values = { 'resource': resource, 'user' : user }		
		path = os.path.join(os.path.dirname(__file__), 'views/enviar.html')
		self.response.out.write(template.render(path,template_values))
	
	def post(self):
		proposta = Proposta()
		voto = Voto()		
		user = Usuario().all().filter("id =",self.request.get("id")).get()
		now = datetime.datetime.now()
		created = (now - datetime.datetime(2009, 3, 28)).days		
		if user:
			proposta.autor = user
			proposta.titulo = self.request.get('title')
			proposta.descricao = self.request.get('bodytext')
			categoria = self.request.get('category')
			if categoria == '1': proposta.categoria  = "Group Fundraiser "
			if categoria == '2': proposta.categoria  = "Campaign"
			if categoria == '3': proposta.categoria  = u"Pledged Action"
			if categoria == '4': proposta.categoria  = "Event"
			if categoria == '5': proposta.categoria  = "Affinity Group"
			if categoria == '6': proposta.categoria  = "Volunteer"
			if categoria == '7': proposta.categoria  = u"Micro-credit Loan"
			if categoria == '8': proposta.categoria  = u"Segurança"
			if categoria == '9': proposta.categoria  = "Trabalho"
			if categoria == '10': proposta.categoria = " Petition"
			if categoria == '11': proposta.categoria = u"Ciência e Tecnologia"	
			if self.request.get('tags'):
				tags = self.request.get('tags')
				tags = tags.replace(' ','')
				proposta.tags = tags.split(",")
			else:
				proposta.tags = self.request.get('title').split(" ")
			proposta.cont = 1
			proposta.created   = created
			proposta.put()
			voto.autor = user
			voto.proposta = self.request.get('title')
			voto.put()
			self.redirect('/novas')	
		
		
class Search(webapp.RequestHandler):
	def get(self):
		template_values = {}
		page = 1
		category = ''
		if self.request.get("page"):
			page = self.request.get("page")		
		numero = 5		
		n = (int(page) * numero) - numero
		if self.request.get('q'):
			tag = self.request.get('q')
			cont = Proposta.all().filter("tags =",tag).count()
			propostas = Proposta.all().filter("tags =",tag).order('-data').fetch(numero,n)
		else:
			propostas = Proposta.all().order('-data').fetch(numero,n)		
			cont = Proposta.all().count()			
		paginas = pagination(cont,numero)
		p = []
		for proposta in propostas:
			p.append(proposta)		   
		user = Usuario().getCurrentUser()	
		if user:
			url = users.create_logout_url(self.request.uri)
			url_linktext = 'Logout'
			status = 'logado'
		else:
			url = users.create_login_url(self.request.uri)
			url_linktext = 'Login'
			status = ''		
		resource = {'title': "Democracia 2 - Search", 'pagename': "Search"}		
		template_values = { 'url': url,
							'url_linktext': url_linktext,
							'status': status,
							'paginas': paginas,
							'category': category,
							'resource': resource,
							'propostas': p
							}
		path = os.path.join(os.path.dirname(__file__), 'views/novas.html')
		self.response.out.write(template.render(path,template_values))	
		
class Action(webapp.RequestHandler):
	def get(self):
		template_values = {}
		user = Usuario().getCurrentUser()
		propostas = Proposta.all().order('-data')		
		if user:
			url = users.create_logout_url(self.request.uri)
			url_linktext = 'Logout'
			status = 'logado'
		else:
			url = users.create_login_url(self.request.uri)
			url_linktext = 'Login'
			status = ''
		comentarios = Comment().all().filter("proposta =",self.request.get('title'))	
		p = []
		for comment in comentarios:
			p.append(comment)			
		title = self.request.get('title')
		proposta = Proposta().all().filter("titulo =",title).get()
		resource = {'title': "Democracia 2 - Action", 'pagename': "Action"}		
		template_values = { 'url': url,
							'url_linktext': url_linktext,
							'status': status,
							'comentarios': p,
							'proposta': proposta,
							'resource': resource
							}		
		path = os.path.join(os.path.dirname(__file__), 'views/comentar.html')
		self.response.out.write(template.render(path,template_values))
	
	def post(self):	
		user = Usuario().getCurrentUser()
		u = users.get_current_user()
		if user:
			comment = Comment()
			comment.autor      =  user
			comment.titulo     =  self.request.get('title')
			comment.comentario =  self.request.get('bodytext')
			comment.proposta   =  self.request.get('proposta')
			comment.put()
			self.redirect('/story?title=' + self.request.get('proposta'))
		
class Votar(webapp.RequestHandler):
	def get(self):	
		user = Usuario().all().filter("id =",self.request.get("id")).get()
		if user:			
			voto = Voto()
			q = Voto.all()
			q.filter("autor =", user)
			q.filter("proposta =", self.request.get('proposta'))
			contador = q.count()
			if contador >= 1:
				self.response.out.write("0")
			else:
				voto.autor = user
				voto.proposta = self.request.get('proposta')
				voto.put()
				proposta = Proposta().all().filter("titulo =", voto.proposta).get()
				cont = proposta.cont
				proposta.rank = (proposta.created * 4) + cont + 1
				proposta.cont = cont + 1;
				proposta.put()
				self.response.out.write(proposta.cont)					
		else:
			self.response.out.write("0")	

class Sobre(webapp.RequestHandler):
	def get(self):
		template_values = {}
		user = Usuario().all().filter("user =",users.get_current_user()).get()	
		if users.get_current_user():
			url = users.create_logout_url(self.request.uri)
			url_linktext = 'Logout'
			status = 'logado'
		else:
			url = users.create_login_url(self.request.uri)
			url_linktext = 'Login'
			status = ''		
		template_values = { 'url': url,
							'user':user,
							'url_linktext': url_linktext,
							'status': status
							}		
		path = os.path.join(os.path.dirname(__file__), 'views/sobre.html')
		self.response.out.write(template.render(path,template_values))
			
			
class Registro(webapp.RequestHandler):
	def get(self):	
		template_values = {}		
		user = Usuario().getCurrentUser()	
		if self.request.get("id"):
			self.criaUsuarioAjax()
			return			
		
	def criaUsuarioAjax(self):
		if not Usuario().all().filter("id =",self.request.get('id')).get():
			user      = Usuario()
			user.nome = self.request.get('nome')
			user.id   = self.request.get('id')
			user.put()
			self.response.out.write("1")
		else:
			self.response.out.write("0")
	
		

class Perfil(webapp.RequestHandler):
	def get(self):	
		user = Usuario().getCurrentUser()
		propostas = Proposta().all().filter("autor =", user)
		comentarios = Comment().all().filter("autor =",user)	
		votos = Voto().all().filter("autor =",user)
		if user:
			url = users.create_logout_url(self.request.uri)
			url_linktext = 'Logout'
			status = 'logado'
		else:
			url = users.create_login_url(self.request.uri)
			url_linktext = 'Login'
			status = ''		
		resource = {'title': "Democracia 2 - Profile", 'pagename': "Profile"}		
		template_values = {	'url'         : url,
							'url_linktext': url_linktext,
							'status'      : status,
							'propostas'   : propostas,
							'comentarios' : comentarios,
							'resource'    : resource,
							'user'        : user,
							'votos'       : votos,
							}			
		path = os.path.join(os.path.dirname(__file__), 'views/perfil.html')
		self.response.out.write(template.render(path,template_values))	

class Blogs(webapp.RequestHandler):
	def get(self):
		template_values = {}
		user = Usuario().all().filter("user =",users.get_current_user())
		user = user.get()		
		if users.get_current_user():
			url = users.create_logout_url(self.request.uri)
			url_linktext = 'Logout'
			status = 'logado'
		else:
			url = users.create_login_url(self.request.uri)
			url_linktext = 'Login'
			status = ''		
		template_values = { 'url': url,
							'user':user,
							'url_linktext': url_linktext,
							'status': status
							}		
		path = os.path.join(os.path.dirname(__file__), 'views/blogs.html')
		self.response.out.write(template.render(path,template_values))
		
class Actions(webapp.RequestHandler):
	def get(self):
		import datetime
		from django.utils import simplejson	
		limit = self.request.get("limit")
		base = "http://search.socialactions.com/actions.json?limit="+limit
		#query = self.request.get("q")
		#query = query.replace(" ","%20")
		query = ""
		url = str(base + query)	
		now = datetime.datetime.now()
		try:
			result = urlfetch.fetch(url)		
			obj = simplejson.loads(result.content)	
		except:
			self.response.out.write("ERRO")
			return	

		now = datetime.datetime.now()
		created = (now - datetime.datetime(2009, 3, 28)).days
		for act in obj:
			if Proposta().all().filter("titulo =",act['title']).get():
				self.response.out.write(act['title']+" not saved<br/>")
			else:	
				proposta           = Proposta()
				proposta.titulo    = act['title']
				proposta.descricao = act['description']
				proposta.cont      = 1
				proposta.categoria = act['action_type']['name']
				proposta.url       = act['url']
				proposta.siteName  = act['site']['name']
				proposta.siteUrl   = act['site']['url']
				proposta.hitcount  = act['hit_count']
				proposta.created   = created
				proposta.tags = act['title'].split(" ")
				proposta.put()
				self.response.out.write(act['title']+" saved<br/>")
	
class FeedParser (webapp.RequestHandler):
	def get(self):
		import feedparser
		url = "http://www.dapper.net/transform.php?dappName=Propostas&transformer=RSS&extraArg_title=Nome&extraArg_description[]=Ementa&v_Query="
		category = ''
		categoria = self.request.get("categoria")
		categorias = ["Cultura", "Economia",u"Educação","Energia","Esportes","Meio Ambiente", u"Saúde", u"Segurança","Trabalho",
						"Transportes", u"Ciência e Tecnologia"]				
		url = url + categoria
		result = urlfetch.fetch(url)
		if categoria ==  "Educacao": categoria = u"Educação"
		if categoria ==  "Ciencia": categoria = u"Ciência e Tecnologia"
		if categoria ==  "Saude": categoria = u"Saúde"	
		d = feedparser.parse(result.content)		
		paginas = []
		i = 1
		pags = len(d.entries)
		paginas = range(1,pags/5)
		self.salvaFeed(d,categoria,5)		
		if users.get_current_user():
			url = users.create_logout_url(self.request.uri)
			url_linktext = 'Logout'
			status = 'logado'
		else:
			url = users.create_login_url(self.request.uri)
			url_linktext = 'Login'
			status = ''			
			
		template_values = { 'url': url,
							'url_linktext': url_linktext,
							'status': status,
							'paginas': paginas,
							'category': category,
							'propostas': d.entries
							}
							
		path = os.path.join(os.path.dirname(__file__), 'views/feed.html')
		self.response.out.write(template.render(path,template_values))		
		
	def salvaFeed(self,d,categoria,n):
		if len(d.entries) < n:
			n = len(d.entries)
		contador = range(0,n)
		contador.reverse()
		for i in contador:
			proposta = Proposta()
			proposta.titulo = d.entries[i].title
			proposta.descricao = d.entries[i].description
			proposta.cont = 1
			proposta.categoria = categoria
			proposta.tags = []
			proposta.put()
		


class IM(webapp.RequestHandler):
	def post(self):
		msg = self.request.get("msg")
		self.response.out.write("A msg foi :" + msg)
		
	
class Canvas(webapp.RequestHandler):
	def get(self):
		template_values = {	}		
		path = os.path.join(os.path.dirname(__file__), 'views/canvas.html')
		self.response.out.write(template.render(path,template_values))
		
class Rpc_relay(webapp.RequestHandler):
	def get(self):
		template_values = {	}		
		path = os.path.join(os.path.dirname(__file__), 'views/rpc_relay.html')
		self.response.out.write(template.render(path,template_values))		
		
	
def pagination(cont,numero):
	pag = cont/numero
	if cont%numero != 0: 
		pag = pag + 1
	paginas = []
	i = 1
	while i <= pag:
		paginas.append(i)
		i = i + 1
	return paginas	

def actionList(propostas):
	p = []
	for proposta in propostas:	
		p.append(proposta)
	return p
	
def main():
	application = webapp.WSGIApplication([('/', Publicadas),
										('/login', Login),
										('/novas', Novas),
										('/perfil',Perfil),
										('/search',Search),
										('/feed',FeedParser),
										('/story', Action),
										('/publicadas', Publicadas),
										('/enviar', Enviar),
										('/sobre', Sobre),
										('/votar', Votar),
										('/actions', Actions),		
										('/register', Registro),											
										('/im',IM),		
										('/canvas.html',Canvas),
										('/rpc_relay.html',Rpc_relay),											
										('/blogs',Blogs)],debug=True)
										
	wsgiref.handlers.CGIHandler().run(application)
		
if __name__ == "__main__":
	main()